/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.afaker.rss.common;

import com.afaker.rss.context.ResourceContext;
import com.afaker.rss.http.HttpConnector;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Runnable;
import java.net.HttpURLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JProgressBar;

/**
 *
 * @author bruce
 */
public class ClientUpdater implements Runnable {
    /* The target file */

    private JProgressBar progressBar;
    public static String CORE_LIB_URL = "http://rssr-eader.googlecode.com/files/RSS_Client.jar";
    public static String DOWNLOAD_PAGE = "http://code.google.com/p/rssr-eader/downloads/list";
    /* Directory where the target file is downloaded to */
    public static String DOWNLOAD_DIR = ResourceContext.getResourceContext().getProperty("update.dir");
    public static String FILE_NAME = "RSS_Client.jar";
    private int fileSize;
    private boolean isDone = false;
    private String regex = "http://\\S+.jar";

    public ClientUpdater() {
    }

    public void setJProgressBar(JProgressBar progressBar) {
        this.progressBar = progressBar;
        if (this.progressBar != null) {
            this.progressBar.setStringPainted(true);
            this.progressBar.setString("Downloading...");
        }
    }

    @Override
    public void run() {
        InputStream input = null;
        FileOutputStream output = null;
        HttpConnector connector = new HttpConnector(DOWNLOAD_PAGE);
        HttpURLConnection connection = null;
        try {
            connection = connector.connect();
        } catch (IOException ex) {
            Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (connection != null) {
            try {
                input = connector.getInputStream(connection);
            } catch (IOException ex) {
                Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        String buffer = "";
        if (input != null) {
            int b;
            try {
                while ((b = input.read()) != -1) {
                    buffer += String.valueOf((char) b);
                }
            } catch (IOException ex) {
                Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(buffer);
        String fileLink = "";
        while (matcher.find()) {
            fileLink = matcher.group();
        }


        connector = new HttpConnector(fileLink);
        boolean isUpdate = connector.load();
        if (!isUpdate) {
            return;
        }
        try {
            connection = connector.connect();
        } catch (IOException ex) {
            Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (connection != null) {
            fileSize = connection.getContentLength();
            initProgressBar();
            try {
                input = connector.getInputStream(connection);
            } catch (IOException ex) {
                Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (input != null) {
            File file = new File(DOWNLOAD_DIR);
            if (!file.exists()) {
                file.mkdir();
            }
            try {
                output = new FileOutputStream(DOWNLOAD_DIR + FILE_NAME);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
                return;
            }
            if (output != null) {
                int b;
                try {
                    while ((b = input.read()) != -1) {
                        updateProgressBar();
                        output.write(b);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                try {
                    output.flush();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                isDone = true;
                try {
                    input.close();
                } catch (IOException ex) {
                    Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    output.close();
                } catch (IOException ex) {
                    Logger.getLogger(ClientUpdater.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void initProgressBar() {
        if (progressBar != null) {
            progressBar.setMaximum(fileSize);
            progressBar.setMinimum(1);
            progressBar.setString("0/" + fileSize / 1024 + "KB 0%");
        }
    }

    private void updateProgressBar() {
        if (progressBar != null) {
            progressBar.setValue(progressBar.getValue() + 1);
            String percent = String.valueOf((float) progressBar.getValue() / fileSize * 100);
            if (percent.length() > 3) {
                percent = percent.substring(0, 4);
            }
            progressBar.setString(progressBar.getValue() / 1024 +
                    "/" + fileSize / 1024 + " KB " +
                    percent + "%");
        }
    }

    public boolean isDone() {
        return isDone;
    }
}
